package com.power.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.power.constant.MemberConstants;
import com.power.domain.Member;
import com.power.ex.handle.BussinessException;
import com.power.mapper.MemberMapper;
import com.power.service.SendService;
import com.power.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Map;

/**
 * @Description 发送短信验证码实现类
 * @Author dingchunlin
 * @Date 2024/07/21 10:27
 * @Version 1.0.0
 */
@Service
public class SendServiceImpl implements SendService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 发送手机验证码
     * @param map
     */
    @Override
    public void sendPhoneCode(Map<String, Object> map) {
        // 首先获取手机号码
        String phone = (String) map.get("phonenum");
        // 然后生成验证码
        String randomNumber = RandomUtil.randomNumbers(4);
        System.out.println("随机验证码：" + randomNumber);
        // 将验证码存入redis
        stringRedisTemplate.opsForValue().set(MemberConstants.MSG_PHONE_PREFIX + phone, randomNumber, Duration.ofMinutes(5));
        // TODO : 后续需要调用第三方接口发送验证码短信
    }

    /**
     * 保存手机号
     * @param map
     * @return
     */
    @Override
    public Boolean saveMsgPhone(Map<String, Object> map) {
        // 首先获取手机号码
        String phone = (String) map.get("phonenum");
        // 获取用户输入的验证码
        String code = (String) map.get("code");
        // 从redis中获取验证码
        String redisCode = stringRedisTemplate.opsForValue().get(MemberConstants.MSG_PHONE_PREFIX + phone);
        // 判断验证码是否过期
        if (!StringUtils.hasText(redisCode)) {
            throw new BussinessException("验证码已过期");
        }
        // 判断验证码是否正确
        if (!redisCode.equals(code)) {
            throw new BussinessException("验证码错误");
        }
        // 保存手机号
        Member member = new Member();
        member.setUserMobile(phone);
        //获取当前用户的openid
        String openId = AuthUtils.getMemberOpenId();
        // 进行修改
        int update = memberMapper.update(member, new LambdaQueryWrapper<Member>()
                .eq(Member::getOpenId, openId));
        // 判断是否修改成功
        if (update <= 0) {
            throw new BussinessException("手机号保存失败");
        }
        // 删除验证码
        stringRedisTemplate.delete(MemberConstants.MSG_PHONE_PREFIX + phone);
        return update > 0;
    }
}
